package org.example.sb_api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.sb_api.common.Result;
import org.example.sb_api.entity.City;
import org.example.sb_api.entity.LocationCity;
import org.example.sb_api.entity.Weather;
import org.example.sb_api.entity.WeatherForecast;
import org.example.sb_api.mapper.CityMapper;
import org.example.sb_api.mapper.LocationCityMapper;
import org.example.sb_api.mapper.WeatherMapper;
import org.example.sb_api.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CityServiceImpl implements CityService {

    @Autowired
    private CityMapper cityMapper;
    
    @Autowired
    private LocationCityMapper locationCityMapper;
    
    @Autowired
    private WeatherMapper weatherMapper;

    @Override
    public Result getCityList() {
        // 获取所有省级城市
        List<City> provinces = cityMapper.selectList(
            new QueryWrapper<City>().eq("pid", 0)
        );
        
        // 获取每个省的下级城市
        for (City province : provinces) {
            List<City> cities = cityMapper.selectList(
                new QueryWrapper<City>().eq("pid", province.getId())
            );
            province.setChildren(cities);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("total", provinces.size());
        result.put("rows", provinces);
        result.put("code", 200);
        
        return Result.success(result);
    }

    @Override
    public Result getLocationCityList() {
        List<LocationCity> cities = locationCityMapper.selectList(null);
        
        Map<String, Object> result = new HashMap<>();
        result.put("total", cities.size());
        result.put("rows", cities);
        result.put("code", 200);
        
        return Result.success(result);
    }

    @Override
    public Result getWeatherList(Long cityId, String cityName) {
        QueryWrapper<Weather> wrapper = new QueryWrapper<>();
        if (cityId != null) {
            wrapper.eq("city_id", cityId);
        }
        if (cityName != null) {
            wrapper.eq("city_name", cityName);
        }
        
        List<Weather> weatherList = weatherMapper.selectList(wrapper);
        for (Weather weather : weatherList) {
            WeatherForecast forecast = weatherMapper.selectForecastByCityId(weather.getCityId());
            weather.setWeatherForecastList(forecast);
        }
        
        return Result.success(weatherList);
    }
} 